package com.zm.cc.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zm.cc.Result;
import com.zm.cc.Utils;
import com.zm.cc.entity.Fav;
import com.zm.cc.entity.Tag;
import com.zm.cc.entity.TagFav;
import com.zm.cc.entity.User;
import com.zm.cc.mapper.FavMapper;
import com.zm.cc.mapper.TagFavMapper;
import com.zm.cc.mapper.TagMapper;
import com.zm.cc.service.BizException;
import com.zm.cc.service.IFavService;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet("/queryTagFav")
public class QueryTagFavServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user = new User();
        user.setId(1);
        Integer uid = user.getId();

        ApplicationContext cxt = (ApplicationContext) this.getServletContext().getAttribute("cxt");
        FavMapper favMapper = cxt.getBean(FavMapper.class);
        TagMapper tagMapper = cxt.getBean(TagMapper.class);
        TagFavMapper tagFavMapper = cxt.getBean(TagFavMapper.class);


        LambdaQueryWrapper<Fav> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Fav::getUid,uid);
        List<Fav> favs = favMapper.selectList(lqw1);

        LambdaQueryWrapper<Tag> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(Tag::getUid,uid);
        List<Tag> tags = tagMapper.selectList(lqw2);

        List<TagFav> tagFavs = null;
       if(tags.size()>0&&favs.size()>0){
           LambdaQueryWrapper<TagFav> lqw3 = new LambdaQueryWrapper<>();
           lqw3.in(TagFav::getTid,tags.stream()
                   .map(tag -> tag.getId())
                   .collect(Collectors.toList())
           );
            tagFavs = tagFavMapper.selectList(lqw3);
       }

        Map<String,Object> map = new HashMap<>();
        map.put("favs",favs);
        map.put("tags",tags);
        map.put("tagFavs",tagFavs);
        Result result = new Result();
        result.setCode(1);
        result.setMsg("搜索成功");
        result.setData(map);
        Utils.print(resp,result);
    }
}
